console.log('Mock.js 已加载')
import Mock from 'mockjs'
import type { MockjsRequestOptions } from 'mockjs'

// 存储验证码的Map，key为手机号，value为{code: 验证码, timestamp: 发送时间}
const smsCodeMap = new Map<string, { code: string; timestamp: number }>()

// 生成6位随机验证码
const generateCode = () => {
  return Math.floor(100000 + Math.random() * 900000).toString()
}

// 验证码是否在有效期内（5分钟）
const isCodeValid = (timestamp: number) => {
  return Date.now() - timestamp <= 5 * 60 * 1000
}

// 解析请求参数
const parseRequestBody = (body: string | FormData): Record<string, string> => {
  const params: Record<string, string> = {}

  console.log('🔍 解析请求体，类型:', typeof body, '是否为FormData:', body instanceof FormData)

  if (body instanceof FormData) {
    console.log('📋 处理FormData格式')
    for (const [key, value] of body.entries()) {
      params[key] = value.toString()
      console.log(`📋 FormData字段: ${key} = ${value}`)
    }
  } else if (typeof body === 'string') {
    console.log('📋 处理字符串格式:', body)
    try {
      const parsed = JSON.parse(body)
      console.log('📋 JSON解析结果:', parsed)
      return parsed
    } catch {
      console.log('📋 尝试URLSearchParams解析')
      const searchParams = new URLSearchParams(body)
      for (const [key, value] of searchParams.entries()) {
        params[key] = value
        console.log(`📋 URLSearchParams字段: ${key} = ${value}`)
      }
    }
  }

  console.log('📋 最终解析结果:', params)
  return params
}

// 发送短信验证码
Mock.mock('/api/sms/sendCode', 'post', (options: MockjsRequestOptions) => {
  console.log('📡 Mock 发送验证码接口被调用:', options.url)
  console.log('📡 请求体:', options.body)

  try {
    const params = parseRequestBody(options.body)
    const { mobile } = params

    console.log('📱 解析后的参数:', { mobile })

    // 验证手机号格式
    if (!mobile || !/^1[3-9]\d{9}$/.test(mobile)) {
      console.log('❌ 手机号格式不正确:', mobile)
      return {
        code: '400',
        message: '手机号格式不正确',
        data: null
      }
    }

    // 检查是否频繁发送
    const existingCode = smsCodeMap.get(mobile)
    if (existingCode && Date.now() - existingCode.timestamp < 60 * 1000) {
      console.log('❌ 发送太频繁:', mobile)
      return {
        code: '400',
        message: '发送太频繁，请稍后再试',
        data: null
      }
    }

    // 生成新的验证码
    const code = generateCode()
    smsCodeMap.set(mobile, {
      code,
      timestamp: Date.now()
    })

    console.log(`✅ 手机号 ${mobile} 的验证码为: ${code}`)

    return {
      code: '100',
      message: '发送成功',
      data: null
    }
  } catch (error: unknown) {
    console.error('❌ 发送验证码失败:', error)
    return {
      code: '500',
      message: '发送失败',
      data: null
    }
  }
})

// 验证短信验证码
Mock.mock('/api/sms/verifyCode', 'post', (options: MockjsRequestOptions) => {
  try {
    const params = parseRequestBody(options.body)
    const { mobile, code } = params

    console.log('🔍 验证码验证请求:', { mobile, code })

    // 验证手机号格式
    if (!mobile || !/^1[3-9]\d{9}$/.test(mobile)) {
      return {
        code: '400',
        message: '手机号格式不正确',
        data: null
      }
    }

    // 验证验证码格式
    if (!code || !/^\d{6}$/.test(code)) {
      return {
        code: '400',
        message: '验证码格式不正确',
        data: null
      }
    }

    // 检查是否是固定测试账号的验证码
    const isTestAccount = (
      (mobile === '13588816882' && code === '123456') ||
      (mobile === '13857185554' && code === '123456') ||
      (mobile === '13000000002' && code === '123456') ||
      (mobile === '13800000000' && code === '123456') ||
      (mobile === '13800000001' && code === '123456') ||
      (mobile === '13800000002' && code === '123456')
    )

    if (isTestAccount) {
      console.log('✅ 固定测试账号验证码验证成功')
      return {
        code: '100',
        message: '验证成功',
        data: null
      }
    }

    // 获取存储的验证码
    const storedCode = smsCodeMap.get(mobile)
    if (!storedCode) {
      return {
        code: '400',
        message: '请先获取验证码',
        data: null
      }
    }

    // 验证码是否过期
    if (!isCodeValid(storedCode.timestamp)) {
      smsCodeMap.delete(mobile) // 删除过期的验证码
      return {
        code: '400',
        message: '验证码已过期，请重新获取',
        data: null
      }
    }

    // 验证码是否正确
    if (storedCode.code !== code) {
      console.log('❌ 验证码不匹配:', { input: code, stored: storedCode.code })
      return {
        code: '400',
        message: '验证码错误',
        data: null
      }
    }

    // 验证成功后删除验证码
    smsCodeMap.delete(mobile)
    console.log('✅ 动态验证码验证成功')

    return {
      code: '100',
      message: '验证成功',
      data: null
    }
  } catch (error: unknown) {
    console.error('验证码验证失败:', error)
    return {
      code: '500',
      message: '验证失败',
      data: null
    }
  }
})

// 管理端登录
Mock.mock('/api/login/adminLogin', 'post', (options: MockjsRequestOptions) => {
  console.log('📡 Mock 管理端登录接口被调用:', options.url)

  // 处理 FormData 格式的请求体
  let mobile = '', code = ''
  if (options.body instanceof FormData) {
    mobile = options.body.get('mobile') as string
    code = options.body.get('code') as string
  } else {
    try {
      const body = JSON.parse(options.body)
      mobile = body.mobile
      code = body.code
    } catch (e) {
      console.log('❌ 解析请求体失败:', e)
    }
  }
  console.log('📝 登录参数:', { mobile, code })

  // 超级管理员：全部权限
  if (mobile === '13588816882' && code === '123456') {
    const loginInfo = {
      token: Mock.Random.guid(),
      user: {
        user: {
          id: 2,
          userType: '后台管理',
          mobile: mobile,
          userName: '超级管理员',
          nickname: '超级管理员',
          avatar: null,
          status: '启用',
          createdAt: '2025-06-16 20:40:26',
          updatedAt: null,
          deletedAt: null
        },
        roleList: [
          {
            id: 1,
            roleName: '超级管理员',
            type: '系统角色'
          }
        ],
        permissionList: [
          { id: null, roleId: null, permissionCode: '0101', permissionName: '控制台查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0201', permissionName: '开票申请审核查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0301', permissionName: '投诉举报查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0401', permissionName: '意见反馈查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0501', permissionName: '工具管理查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0601', permissionName: '活动管理查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0701', permissionName: '企业管理查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0801', permissionName: '用户管理查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0901', permissionName: '资金明细查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '1001', permissionName: '发票管理查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '1101', permissionName: '活动管理员管理查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '1102', permissionName: '客服专员管理管理查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '1201', permissionName: '查看个人账号信息', createdAt: null },
          { id: null, roleId: null, permissionCode: '1203', permissionName: '查看账号权限管理', createdAt: null },
          { id: null, roleId: null, permissionCode: '1301', permissionName: '查看登录日志', createdAt: null },
          { id: null, roleId: null, permissionCode: '1302', permissionName: '查看操作日志', createdAt: null },
          { id: null, roleId: null, permissionCode: '1401', permissionName: '意见反馈查看', createdAt: null }
        ]
      }
    }
    return {
      code: '100',
      message: '登录成功',
      data: loginInfo
    }
  }
  // 企业账号：企业管理、账号信息
  else if (mobile === '13800000000' && code === '123456') {
    const loginInfo = {
      token: Mock.Random.guid(),
      user: {
        user: {
          id: 3,
          userType: '后台管理',
          mobile: mobile,
          userName: '企业账号',
          nickname: '企业账号',
          avatar: null,
          status: '启用',
          createdAt: '2025-06-16 20:40:26',
          updatedAt: null,
          deletedAt: null
        },
        roleList: [
          {
            id: 2,
            roleName: '企业账号',
            type: '系统角色'
          }
        ],
        permissionList: [
          { id: null, roleId: null, permissionCode: '0701', permissionName: '企业管理查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '1201', permissionName: '查看个人账号信息', createdAt: null },
          { id: null, roleId: null, permissionCode: '1203', permissionName: '查看账号权限管理', createdAt: null }
        ]
      }
    }
    return {
      code: '100',
      message: '登录成功',
      data: loginInfo
    }
  }
  // 活动工具账号：活动管理、工具管理
  else if (mobile === '13800000001' && code === '123456') {
    const loginInfo = {
      token: Mock.Random.guid(),
      user: {
        user: {
          id: 4,
          userType: '后台管理',
          mobile: mobile,
          userName: '活动工具账号',
          nickname: '活动工具账号',
          avatar: null,
          status: '启用',
          createdAt: '2025-06-16 20:40:26',
          updatedAt: null,
          deletedAt: null
        },
        roleList: [
          {
            id: 3,
            roleName: '活动工具账号',
            type: '系统角色'
          }
        ],
        permissionList: [
          { id: null, roleId: null, permissionCode: '0501', permissionName: '工具管理查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0601', permissionName: '活动管理查看', createdAt: null }
        ]
      }
    }
    return {
      code: '100',
      message: '登录成功',
      data: loginInfo
    }
  }
  // 待办账号：待办中心相关
  else if (mobile === '13800000002' && code === '123456') {
    const loginInfo = {
      token: Mock.Random.guid(),
      user: {
        user: {
          id: 5,
          userType: '后台管理',
          mobile: mobile,
          userName: '待办账号',
          nickname: '待办账号',
          avatar: null,
          status: '启用',
          createdAt: '2025-06-16 20:40:26',
          updatedAt: null,
          deletedAt: null
        },
        roleList: [
          {
            id: 4,
            roleName: '待办账号',
            type: '系统角色'
          }
        ],
        permissionList: [
          { id: null, roleId: null, permissionCode: '0201', permissionName: '开票申请审核查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0301', permissionName: '投诉举报查看', createdAt: null },
          { id: null, roleId: null, permissionCode: '0401', permissionName: '意见反馈查看', createdAt: null }
        ]
      }
    }
    return {
      code: '100',
      message: '登录成功',
      data: loginInfo
    }
  }
  // ...其他账号...
  else {
    console.log('❌ 登录失败：手机号或验证码错误')
    return {
      code: '902',
      message: '登录失败',
      data: null
    }
  }
})

// 导出默认函数以支持动态导入
export default function setupMock() {
  console.log('Mock 设置完成')
}
